#include "TCP.h"

TCP::TCP(int t_port, char* t_addr) :Port(t_port) {
	addr = new char[50];
	strcpy(addr, t_addr);
}

TCP::~TCP() {
	delete[] addr;
}

int TCP::Init() {
	socklen_t slen = sizeof(sock_server);
	socklen_t clen = sizeof(sock_client);
	int on = 1;

	sock_server.sin_family = AF_INET;
	sock_server.sin_port = htons(Port);
	sock_server.sin_addr.s_addr = INADDR_ANY;


	sfd = socket(AF_INET, SOCK_STREAM, 0);
	setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	if (sfd < 3) {
		cout << "Socket ERROR" << endl;
		return -1;
	}

	int res = bind(sfd, (struct sockaddr *)&sock_server, slen);
	if (res < 0) {
		cout << "Bind ERROR" << endl;
		return -1;
	}

	res = listen(sfd, 10);
	cfd = accept(sfd, (struct sockaddr *)&sock_client, &clen);
	if (cfd < 3)	return -1;
	cout << "Connect Complete" << endl;
	return sfd;
}
int TCP::Send_Message(char *arr){
	char send_buf[100] = { 0 };
	strcpy(send_buf, arr);
	int res = send(cfd, send_buf, strlen(send_buf), 0);
	cout << "已发送" << endl;
	return res;
};


int TCP::Recv_Message(char *arr){
	char recv_buf[100] = { 0 };
	int res = recv(cfd, recv_buf, sizeof(recv_buf), 0);
	cout << "已接受" << endl;
	strcpy(arr, recv_buf);
	cout << arr << endl;
	return res;
};


